﻿Public Class Frm_INTElementSplit
    Implements IDServer.IDServer.IDServer

#Region " Variable and Property "

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#End Region

#Region " interface "

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If App.AddEnable = False Then
            Msg.MsgError("您沒有添加的權限")
            Exit Function
        End If
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        Me.SetButton(ButtonType.Add, False)
        Me.setControlStatus()
        Me.TabControl1.SelectedIndex = 1
        Me.txtElement.Focus()
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        Me.SetButton(ButtonType.Cancel, False)
        Me.setControlStatus(True)
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint
        If App.PrintEnable = False Then
            Msg.MsgError("您沒有列印的權限")
            Exit Function
        End If
        Try
            Dim Sql As String = String.Empty
            Dim mServer As String = String.Empty
            Dim mDatabase As String = String.Empty
            Dim mUid As String = String.Empty
            Dim mPwd As String = String.Empty
            Dim PathStr As String = String.Empty

            Dim Element As String = String.Empty
            Dim ElementStr As System.Text.StringBuilder = New System.Text.StringBuilder

            Dim ConfigureNode() As String = ReadConfigFile.Split(";")

            PathStr = GetReportPath("Store", "RepElement.rpt")

            Select Case Me.TabControl1.SelectedIndex
                Case 0
                    If Not Me.DGVSplitRecords.CurrentCell Is Nothing Then
                        Dim sqls As String = "select ''''+replace(newElements,',',''',''')+'''' as NewElements from dbo.Stor_Elementsplit  where BoNum='" + Me.DGVSplitRecords.Rows(Me.DGVSplitRecords.CurrentCell.RowIndex).Cells("BoNum").Value.ToString() + "'"
                        Dim result As Object = Exec(sqls, E_ExecType.ExecuteScalar)
                        If Not result Is System.DBNull.Value Then
                            ElementStr.Append(result)
                        Else
                            ElementStr.Append("'" + "'")
                        End If
                    End If
                Case 1
                    If Me.DGVElementDetail.RowCount > 0 Then
                        For i As Integer = 0 To Me.DGVElementDetail.Rows.Count - 1
                            Element = Me.DGVElementDetail.Rows(i).Cells("element").Value & ""
                            If ElementStr.Length > 0 Then
                                ElementStr.Append(",")
                            End If
                            ElementStr.Append("'")
                            ElementStr.Append(Element)
                            ElementStr.Append("'")
                        Next
                    Else
                        ElementStr.Append("'" + "'")
                    End If
            End Select
            Dim Newstr As String = ElementStr.ToString
            If Newstr.Replace("'", "").Length = 0 Then
                MessageBox.Show("沒有元件可以列印，請選擇元件號", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2)
                Exit Function
            End If


            If ConfigureNode.Length > 0 Then
                For i As Integer = 0 To ConfigureNode.Length - 1
                    If ConfigureNode(i).Split("=")(0).ToLower = "Server".ToLower Then
                        mServer = ConfigureNode(i).Split("=")(1)
                    End If
                    If ConfigureNode(i).Split("=")(0).ToLower = "Database".ToLower Then
                        mDatabase = ConfigureNode(i).Split("=")(1)
                    End If
                    If ConfigureNode(i).Split("=")(0).ToLower = "Uid".ToLower Then
                        mUid = ConfigureNode(i).Split("=")(1)
                    End If
                    If ConfigureNode(i).Split("=")(0).ToLower = "Pwd".ToLower Then
                        mPwd = ConfigureNode(i).Split("=")(1)
                    End If
                Next
            End If

            Dim MyReportDocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
            Dim LogOnInfo As New CrystalDecisions.Shared.TableLogOnInfo
            Dim Table As CrystalDecisions.CrystalReports.Engine.Table

            MyReportDocument.Load(PathStr)
            For Each Table In MyReportDocument.Database.Tables
                LogOnInfo = Table.LogOnInfo
                With LogOnInfo.ConnectionInfo
                    .ServerName = mServer
                    .DatabaseName = mDatabase
                    .UserID = mUid
                    .Password = mPwd
                End With
                Table.ApplyLogOnInfo(LogOnInfo)
            Next



            Sql = "select '*'+a.Element+'*' as Element,'S/N:'+a.Element as ElementNo,b.supperitem"
            Sql += " as supperitem,b.enname as enname from dbo.Stor_Elmentstatus a "
            Sql += " left join bsc_goods b "
            Sql += " on a.barcode=b.barcode "
            Sql += " where a.element in (" + Newstr + ")"
            Dim dt As DataTable = Exec(Sql, E_ExecType.DataTable)
            If dt.Rows.Count = 0 Then
                Sql = "select '*'+a.Element+'*' as Element,'S/N:'+a.Element as ElementNo,b.supperitem as supperitem,b.enname as enname from dbo.Stor_element a left join bsc_goods b on a.goodsbarcode=b.barcode where a.element in (" + Newstr + ")"
                dt = Exec(Sql, E_ExecType.DataTable)
                If dt.Rows.Count = 0 Then
                    Sql = "select '*'+a.Element+'*' as Element,'S/N:'+a.Element as ElementNo,b.supperitem as supperitem,b.enname as enname from dbo.Stor_ElementOut a left join bsc_goods b on a.goodsbarcode=b.barcode where a.element in (" + Newstr + ")"
                    dt = Exec(Sql, E_ExecType.DataTable)
                End If
            End If

            If dt.Rows.Count = 0 Then
                Msg.MsgOK("找不到需要列印的元件信息")
                Exit Function
            End If
            MyReportDocument.SetDataSource(dt)
            My.Forms.Frm_Report.CrystalReportViewer1.ReportSource = MyReportDocument
            My.Forms.Frm_Report.CrystalReportViewer1.Zoom(1)
            My.Forms.Frm_Report.CrystalReportViewer1.DisplayGroupTree = False
            Frm_Report.ShowDialog()

        Catch ex As Exception
            MessageBox.Show("Error: " + ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            If App.AddEnable = False Then
                Msg.MsgOK("您沒有新增的權限", App.CompanyName)
            End If
            If Me.DGVElementDetail.RowCount = 0 Then
                Msg.MsgError("没有任何拆分数据")
                Exit Function
            End If
            Dim sqlfomart As String = "insert into dbo.Stor_Elmentstatus(storehouse, barcode,element, qty, unit, elementbatch, place, status)" + vbNewLine + "select  storehouse, barcode, '{0}', '{1}', unit,elementbatch, place, status  from Stor_Elmentstatus where element ='{2}'"
            Dim sqlNumFomart As String = String.Empty
            Dim sqlstr As New System.Text.StringBuilder
            Dim bonum As String
            Dim newElements(Me.DGVElementDetail.RowCount - 1) As String
            Dim sql As String = ""
            bonum = Exec(" exec returnBillNum 'Stor_Elementsplit','bonum','S" + App.PubCompanyCode + "'", E_ExecType.ExecuteScalar).ToString()
            sqlNumFomart = "insert into Stor_Elementsplit values('" + bonum + "', '" + Me.txtElement.Text.Replace("*", "") + "', '{0}', '" + App.PubUserCode + "', getDate(), '" + My.Computer.Name + "', '" + Me.txtRemark.Text.Replace("'", "") + "')"
            Dim elementNo As Long = 1
            For index As Int32 = 0 To Me.DGVElementDetail.RowCount - 1
                If elementNo = 1 Then
                    sql = "select * from Number where BillType='ElementNum';"
                    sql += "select * from Stor_element where Element in (select right('0000000000000'+Convert(varchar(20),Number),13) from Number where BillType='ElementNum')"
                    Dim dtTable As DataSet = Exec(sql, E_ExecType.DataSet)
                    If dtTable.Tables(1).Rows.Count > 0 Then
                        Msg.MsgError("生成元件號錯誤，該元件已經存在資料庫中！")
                        Exit Function
                    End If
                    If dtTable.Tables(0).Rows.Count > 0 Then
                        elementNo = Val(dtTable.Tables(0).Rows(0).Item("Number")) + 1
                    Else
                        elementNo = 1
                    End If
                Else
                    elementNo = elementNo + 1
                End If
                newElements(index) = Format(elementNo, "0000000000000") & "X" + "^" + Me.DGVElementDetail.Rows(index).Cells("Qty").Value.ToString()
            Next

            Dim nums As String = String.Empty
            For index1 As Integer = 0 To newElements.Length - 1
                If Not newElements(index1) Is Nothing Then
                    nums = nums + newElements(index1).Split("^")(0)
                    If index1 < newElements.Length - 1 Then
                        nums = nums + ","
                    End If
                End If
            Next

            sqlstr.AppendLine(String.Format(sqlNumFomart, nums))
            sqlstr.AppendLine("update Number  set  number=" & Val(elementNo) & ",UpdatePerson='" & App.PubUserCode & "',UpdateComputer='" & My.Computer.Name & "',UpdateDate='" & Now.Date & "' where  billtype= 'ElementNum'")
            For Each element As String In newElements
                If Not element Is Nothing Then
                    sqlstr.AppendLine(String.Format(sqlfomart, element.Split("^")(0), element.Split("^")(1), Me.txtElement.Text.Replace("*", "")))
                End If
            Next

            Dim tb As DataTable = CType(Me.DGVElementDetail.DataSource, DataTable)
            Dim diff As Int32 = Convert.ToInt32(Me.txtElementQty.Text.Trim) - tb.Compute("sum(Qty)", "1=1")
            If diff < 0 Then
                Msg.MsgError("拆分的數量大于元件原來的數量，操作不成功")
                Exit Function
            End If
            sqlstr.AppendLine("update Stor_Elmentstatus set qty='" + diff.ToString() + "' where element='" + Me.txtElement.Text.Replace("'", "").Replace("*", "") + "'")


            Dim result As Object = Exec(sqlstr.ToString(), E_ExecType.ExecuteNonQuery, True)
            Me.SetButton(ButtonType.Browse, False)
            If Not result Is Nothing Then
                Me.txtSplitNum2.Text = bonum

                For index2 As Integer = 0 To newElements.Length - 1
                    If Not newElements(index2) Is Nothing Then
                        Me.DGVElementDetail.Rows(index2).Cells("Element").Value = newElements(index2).Split("^")(0)
                    End If
                Next
                ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
                Me.setControlStatus()
                Msg.MsgOK("保存成功")
            End If
        ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

        End If
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

#End Region

#Region " Events "
    Private Sub BtnQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnQuery.Click
        fiter()
        Me.SetButton(ButtonType.Browse, True)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            Exit Sub
        End If
        Dim frm As New Frm_SelectElement()
        If frm.ShowDialog() = DialogResult.OK Then
            Me.txtElement.Text = frm.ElementSelected
            Me.txtElement_KeyDown(txtElement, New KeyEventArgs(Keys.Enter))
        End If
    End Sub

    Private Sub DGVSplitRecords_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVSplitRecords.CellDoubleClick
        If Me.DGVSplitRecords.RowCount > 0 Then
            If e.RowIndex = -1 Then
                Exit Sub
            Else
                Dim bonum As String = Me.DGVSplitRecords.Rows(e.RowIndex).Cells("Bonum").Value.ToString()
                Dim element As String = Me.DGVSplitRecords.Rows(e.RowIndex).Cells("OrginalElement").Value.ToString()
                Dim sql As String = ""
                txtElement.Text = element
                sql += "select * from Stor_Elmentstatus where element='" + element + "'" + vbNewLine
                sql += "select Element,Qty from dbo.Stor_Elmentstatus a where " + vbNewLine
                sql += "exists" + vbNewLine
                sql += "			( select * from (select *" + vbNewLine
                sql += "		from dbo.Stor_Elementsplit where Bonum ='" + bonum + "' ) b " + vbNewLine
                sql += "      where ''''+replace(newElements,',',''',''')+'''' like '%'''+a.element+'''%' )" + vbNewLine

                Dim DS As DataSet = Exec(sql, E_ExecType.DataSet)

                If DS.Tables(0).Rows.Count = 0 Then
                    Msg.MsgOK("找不到元件:" + element, Msg.CompanyName)
                ElseIf DS.Tables(0).Rows.Count = 1 Then
                    Me.txtElementQty.Text = DS.Tables(0).Rows(0)("Qty")
                    Me.txtSplitNum2.Text = Me.DGVSplitRecords.Rows(e.RowIndex).Cells("Bonum").Value.ToString()
                    Me.txtOperator.Text = Me.DGVSplitRecords.Rows(e.RowIndex).Cells("Operator").Value.ToString()
                    Me.txtOperateDate.Text = CType(Me.DGVSplitRecords.Rows(e.RowIndex).Cells("OperatorDate").Value, DateTime).ToString("yyyy/MM/dd HH:mm:ss")
                    Me.txtRemark.Text = Me.DGVSplitRecords.Rows(e.RowIndex).Cells("Remark").Value.ToString()
                    Me.DGVElementDetail.DataSource = DS.Tables(1)
                    Me.TabControl1.SelectedIndex = 1
                End If
            End If
        End If
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Me.setControlStatus()
    End Sub

    Private Sub DGV_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DGVElementDetail.RowPostPaint, DGVSplitRecords.RowPostPaint, DGVSplitDetail.RowPostPaint
        App.DGV_RowPostPaint(sender, e)
    End Sub


    Private Sub btnSplit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSplitInTwo.Click, btnSplitAveage.Click, btnSplitOnebyOne.Click
        If sender Is Nothing Then
            Msg.MsgError("sender is nothing,but it requied a  Instance Of button type ")
            Exit Sub
        End If

        Dim btnSender As Button = CType(sender, Button)
        If btnSender Is Nothing Then
            Msg.MsgError(sender.ToString() + " is not button type ")
            Exit Sub
        End If

        Dim element As String = Me.txtElement.Text.Replace("'", "").Replace("*", "").Trim
        If element.Length < 3 Then
            Msg.MsgError("請錄入正確的元件號")
            Me.txtElement.Focus()
            Me.txtElement.SelectAll()
            Exit Sub
        End If

        ''重新查詢確保元件數量是最新的數量
        Dim sqls As String = "select * from Stor_Elmentstatus where element='" + element + "'"
        Dim DS As DataSet = Exec(sqls, E_ExecType.DataSet)
        If DS.Tables(0).Rows.Count = 0 Then
            Msg.MsgOK("找不到元件:" + element, Msg.CompanyName)
            Me.txtElement.Text = ""
            Me.txtElement.Focus()
            Me.txtElement.SelectAll()
            Exit Sub
        ElseIf DS.Tables(0).Rows.Count = 1 Then
            Me.txtElementQty.Text = DS.Tables(0).Rows(0)("Qty")
        End If

        Dim succed As Boolean = False
        If Not IsNumeric(Me.txtElementQty.Text) Then
            Msg.MsgError("操作失败")
            Exit Sub
        End If
        If btnSender Is Me.btnSplitOnebyOne Then
            If IsNumeric(Me.txtQtyOnebyOne.Text) = False Then
                Msg.MsgError("沒有錄入" + Me.Label11.Text.Replace("：", ""))
                txtQtyOnebyOne.Focus()
                Return
            End If
            succed = splitOperate(splitType.SplitOneByOne)
        ElseIf btnSender Is Me.btnSplitAveage Then
            If IsNumeric(Me.txtQtyAverage.Text) = False Then
                Msg.MsgError("沒有錄入" + Me.Label12.Text.Replace("：", ""))
                Me.txtQtyAverage.Focus()
                Return
            End If
            succed = splitOperate(splitType.SplitAveage)
        ElseIf btnSender Is Me.btnSplitInTwo Then
            succed = splitOperate(splitType.SplitInTwo)
        End If
        If succed = False Then
            Msg.MsgError("操作失败")
        End If
    End Sub


    Private Sub txtElement_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtElement.KeyDown
        If e.KeyCode = Keys.Enter And txtElement.TextLength > 0 Then
            Dim element As String = txtElement.Text.Trim().Replace("*", "")
            Dim sql As String = "select * from Stor_Elmentstatus where element='" + element + "'"
            ' sql += "select bonum from  Stor_Elementsplit where OrginalElement='" + element + "'"
            Dim DS As DataSet = Exec(sql, E_ExecType.DataSet)
            If DS.Tables(0).Rows.Count = 0 Then
                Msg.MsgOK("找不到元件:" + element, Msg.CompanyName)
                Me.txtElement.Text = ""
            ElseIf DS.Tables(0).Rows.Count = 1 Then
                Me.txtElementQty.Text = DS.Tables(0).Rows(0)("Qty")
                Me.txtRemark.Focus()
                'If DS.Tables(1).Rows.Count = 1 Then
                '    Me.txtSplitNum2.Text = DS.Tables(1).Rows(0)("Bonum").ToString()
                'End If
            End If
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        If TypeOf Me.DGVElementDetail.DataSource Is DataTable Then
            CType(Me.DGVElementDetail.DataSource, DataTable).Rows.Clear()
        End If
    End Sub

    Private Sub DGVSplitRecords_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DGVSplitRecords.CurrentCellChanged
        If Me.DGVSplitRecords.CurrentCell Is Nothing Then
            If TypeOf Me.DGVSplitDetail.DataSource Is DataTable Then
                CType(Me.DGVSplitDetail.DataSource, DataTable).Rows.Clear()
                Exit Sub
            End If
        End If



        Dim index As Int32 = Me.DGVSplitRecords.CurrentCell.RowIndex
        Dim bonum As String = Me.DGVSplitRecords.Rows(index).Cells("Bonum").Value.ToString()
        Dim element As String = Me.DGVSplitRecords.Rows(index).Cells("OrginalElement").Value.ToString()
        Dim sql As String
        sql = "select * from Stor_Elmentstatus where element='" + element + "'" + vbNewLine
        sql += " union select * from dbo.Stor_Elmentstatus a where " + vbNewLine
        sql += "exists" + vbNewLine
        sql += "			( select * from (select *" + vbNewLine
        sql += "		from dbo.Stor_Elementsplit where Bonum ='" + bonum + "' ) b " + vbNewLine
        sql += "      where ''''+replace(newElements,',',''',''')+'''' like '%'''+a.element+'''%' )" + vbNewLine
        Dim dt As DataTable = Exec(sql, E_ExecType.DataTable)
        If dt.Columns.Contains("ID") Then
            dt.Columns.Remove("ID")
            dt.AcceptChanges()
        End If
        Me.DGVSplitDetail.DataSource = dt
    End Sub

    Private Sub Frm_INTElementSplit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim captionstr1 As String = "拆分單號^BoNum&貨品條碼^BarCode&原元件^OrginalElement&拆分后的元件^NewElements&操作者^Operator&操作時間^OperatorDate&操作電腦^OperatorComputer&備注^Remark"
        Dim captionstr2 As String = "倉別^storehouse&貨品條碼^barcode&元件^element&數量^qty&單位^unit&元件批次^elementbatch&庫位^place&狀態^status"
        Dim captionstr3 As String = "元件^Element&數量^Qty"
        App.DataBindGridView(Me.DGVSplitRecords, captionstr1)
        App.DataBindGridView(Me.DGVSplitDetail, captionstr2)
        App.DataBindGridView(Me.DGVElementDetail, captionstr3)
        Me.DGVElementDetail.Columns("Qty").ValueType = GetType(Int32)
        Me.DGVSplitDetail.AllowUserToAddRows = False
        Me.DGVSplitDetail.ReadOnly = True
    End Sub

#Region "      實現刪除菜單相關的事件和變量     "

    Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuDel.Click
        'If hit Is Nothing Then
        '    Exit Sub
        'ElseIf hit.Type = DataGridViewHitTestType.Cell Or hit.Type = DataGridViewHitTestType.RowHeader Then
        '    Me.DGVElementDetail.Rows.RemoveAt(hit.RowIndex)
        'End If
        If Me.DGVElementDetail.CurrentCell Is Nothing Then
            Exit Sub
        Else
            Me.DGVElementDetail.Rows.RemoveAt(Me.DGVElementDetail.CurrentCell.RowIndex)
        End If
    End Sub

    'Dim hit As System.Windows.Forms.DataGridView.HitTestInfo
    '為什么HitTest不行呢？
    Private Sub DGVElementDetail_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DGVElementDetail.MouseDown
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            Me.DGVElementDetail.ContextMenuStrip = Nothing
            Exit Sub
        Else
            Me.DGVElementDetail.ContextMenuStrip = Me.ContextMenuStrip1
        End If
        '    Dim width As Int32 = Me.DGVElementDetail.RowHeadersWidth
        '    hit = Me.DGVSplitDetail.HitTest(e.X, e.Y)
        '    If hit.Type = DataGridViewHitTestType.Cell Or hit.Type = DataGridViewHitTestType.RowHeader Then
        '        Me.DGVElementDetail.ContextMenuStrip = Me.ContextMenuStrip1
        '    Else
        '        Me.DGVElementDetail.ContextMenuStrip = Nothing
        '    End If
    End Sub

#End Region

#End Region

#Region " Methods "
    Private Function splitOperate(ByVal type As splitType) As Boolean
        Me.DGVElementDetail.AllowUserToAddRows = False
        Dim isSucced As Boolean = False
        Dim tb As New DataTable()
        tb.Columns.Add("Element")
        tb.Columns.Add("Qty", GetType(Int32))

        If Not Me.DGVElementDetail.DataSource Is Nothing Then
            For Each row As DataGridViewRow In Me.DGVElementDetail.Rows
                Dim newrow As DataRow = tb.NewRow()
                newrow("Element") = row.Cells("Element").Value.ToString()
                newrow("Qty") = Convert.ToInt32(row.Cells("Qty").Value.ToString())
                tb.Rows.Add(newrow)
            Next
        End If

        tb.AcceptChanges()
        Dim diff As Int32
        Dim count As Int32 = 0
        If (tb.Rows.Count > 0) Then
            diff = Convert.ToInt32(Me.txtElementQty.Text.Trim) - tb.Compute("sum(Qty)", "1=1")
        Else
            diff = Convert.ToInt32(Me.txtElementQty.Text.Trim)
        End If



        Select Case type
            Case splitType.SplitOneByOne
                count = Convert.ToInt32(Me.txtQtyOnebyOne.Text)
                If diff <= 0 Or (diff < count) Then
                    Return False
                Else
                    Dim row As DataRow = tb.NewRow()
                    row("Element") = ""
                    row("Qty") = count
                    tb.Rows.Add(row)
                    isSucced = True
                End If
                tb.AcceptChanges()

            Case splitType.SplitAveage
                If diff <= 0 Then '數量小于或等于0，不能拆分
                    Return False
                    'ElseIf diff <> Convert.ToInt32(Me.txtElementQty.Text) Then '數量不再是原元件的數量，不能平均拆分
                    '    Return False
                ElseIf (diff Mod Convert.ToInt32(Me.txtQtyAverage.Text)) <> 0 Then '平均拆分有余數，所以不能拆分
                    Return False
                Else
                    count = (diff / Convert.ToInt32(Me.txtQtyAverage.Text))

                    For index As Integer = 1 To Convert.ToInt32(Me.txtQtyAverage.Text)
                        Dim row As DataRow = tb.NewRow()
                        row("Element") = ""
                        row("Qty") = count
                        tb.Rows.Add(row)
                        isSucced = True
                    Next
                End If
                tb.AcceptChanges()

            Case splitType.SplitInTwo
                If diff <= 0 Then '數量小于或等于0，不能拆分
                    Return False
                    'ElseIf diff <> Convert.ToInt32(Me.txtElementQty.Text) Then '數量不再是原元件的數量，不能平均拆分
                    '    Return False
                ElseIf (diff Mod 2) <> 0 Then '平均拆分有余數，所以不能拆分
                    Return False
                Else
                    count = (diff / 2)
                    For index As Integer = 1 To 2
                        Dim row As DataRow = tb.NewRow()
                        row("Element") = ""
                        row("Qty") = count
                        tb.Rows.Add(row)
                        isSucced = True
                    Next
                End If
        End Select
        Me.DGVElementDetail.DataSource = tb
        Me.DGVElementDetail.Update()
        Return isSucced
    End Function

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = False
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = False
                        .ToolStripFilter.Enabled = False

                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = False
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = False

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
            If Me.DGVSplitDetail.RowCount = 0 And Me.DGVElementDetail.RowCount = 0 Then
                MainForm.ToolStripPrint.Enabled = False
            Else
                MainForm.ToolStripPrint.Enabled = True
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Public Enum splitType
        SplitOneByOne
        SplitAveage
        SplitInTwo
    End Enum

    Private Sub fiter()
        Dim sql As String = String.Empty
        sql += "select BoNum, barcode,OrginalElement, NewElements, Operator, OperatorDate, OperatorComputer, Remark from Stor_Elementsplit a left join dbo.Stor_Elmentstatus b on a.OrginalElement=b.element where 1=1 "
        If Me.CheckBox1.Checked Then
            sql += " and  CONVERT(nvarchar(10),OperatorDate,21)=CONVERT(nvarchar(10), Convert(DateTime, '" + Me.DateTimePicker1.Value.ToString("yyyy/MM/dd HH:mm:ss") + "'),21)"
        End If
        If (Me.txtElement1.TextLength > 0) Then
            sql += " and OrginalElement='" + Me.txtElement1.Text.Trim.Replace("'", "").Replace("*", "") + "'"
        End If
        If (Me.txtOperator1.TextLength > 0) Then
            sql += " and Operator='" + App.PubUserCode + "'"
        End If
        If (Me.txtSplitnum1.TextLength > 0) Then
            sql += " and bonum='" + Me.txtSplitnum1.Text.Replace("'", "").Replace("*", "") + "'"
        End If
        Me.DGVSplitRecords.DataSource = Exec(sql, E_ExecType.DataTable)
    End Sub

    Private Sub setControlStatus(Optional ByVal IfClear As Boolean = False)
        If IfClear = True Then
            For Each col As Control In Me.TabPage2.Controls
                If TypeOf col Is TextBox Then
                    CType(col, TextBox).Text = ""
                End If
            Next
            For Each col2 As Control In Me.GroupBox2.Controls
                If TypeOf col2 Is TextBox Then
                    CType(col2, TextBox).Text = ""
                End If
            Next
            If Not Me.DGVElementDetail.DataSource Is Nothing Then
                CType(Me.DGVElementDetail.DataSource, DataTable).Rows.Clear()
            End If
        End If
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
            Me.txtElement.ReadOnly = True
            Me.txtElementQty.ReadOnly = True
            Me.txtOperator.ReadOnly = True
            Me.txtSplitNum2.ReadOnly = True
            Me.txtRemark.ReadOnly = True
            Me.txtOperateDate.ReadOnly = True
            For Each col2 As Control In Me.GroupBox2.Controls
                If TypeOf col2 Is TextBox Then
                    CType(col2, TextBox).ReadOnly = True
                    CType(col2, TextBox).Text = ""
                ElseIf TypeOf col2 Is Button Then
                    CType(col2, Button).Enabled = False
                End If
            Next
        ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
            Me.txtElement.ReadOnly = False
            Me.txtElement.Text = ""
            Me.txtElementQty.ReadOnly = True
            Me.txtElementQty.Text = ""
            Me.txtOperator.ReadOnly = True
            Me.txtOperator.Text = ""
            Me.txtSplitNum2.ReadOnly = True
            Me.txtSplitNum2.Text = ""
            Me.txtRemark.ReadOnly = False
            Me.txtRemark.Text = ""
            Me.txtOperateDate.ReadOnly = True
            Me.txtOperateDate.Text = ""
            For Each col2 As Control In Me.GroupBox2.Controls
                If TypeOf col2 Is TextBox Then
                    CType(col2, TextBox).ReadOnly = False
                ElseIf TypeOf col2 Is Button Then
                    CType(col2, Button).Enabled = True
                End If
            Next
            If Not Me.DGVElementDetail.DataSource Is Nothing Then
                CType(Me.DGVElementDetail.DataSource, DataTable).Rows.Clear()
            End If
        End If

    End Sub
#End Region




    Private Sub Label6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label6.Click

    End Sub
End Class
